<template>
    <div class="tab-views-container">
        <a-tabs
          v-model:activeKey="activeKey"
          type="editable-card"
          hide-add
          size="small"
          @edit="onEdit"
          @change="onTabChange"
        >
            <a-tab-pane
              v-for="tab in tabs"
              :key="tab.key"
              :tab="tab.title"
              :closable="tabs.length > 1"
            >
            </a-tab-pane>
        </a-tabs>
    </div>
</template>

<script lang='ts' setup>
import { computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';

const route = useRoute()
const router = useRouter()
const store = useStore()

const tabs = computed(()=>store.state.tabs)
const activeKey = computed({
    get: () => store.state.activeKey,
    set: (val) => store.dispatch('setActiveKey', val)
})

//监听标签页路由变化
watch(
    () => route.fullPath,
    () => {
        if(route.meta.noTab) return;
        const { name, fullPath, meta } = route;
        store.dispatch('addTab', {
            key: fullPath,
            title: meta.title,
        });
        store.dispatch('setActiveKey', fullPath)
    },
    {
        immediate: true
    }
)

//标签页切换
const onTabChange = (key:string) =>{
    router.push(key)
}

//标签页编辑
const onEdit = (targetKey :string) =>{
    store.dispatch('removeTab', targetKey)
    if(targetKey === store.state.activeKey){
        const lastTab = store.state.tabs[store.state.tabs.length-1]
        if(lastTab){
            router.push(lastTab.key)
        }else{
            router.push('/')
        }
    }
}

</script>

<style scoped>
:deep(.ant-tabs-nav::before){
    border-bottom: none;
}

:deep(.ant-tabs-card > .ant-tabs-nav .ant-tabs-tab){
    border: unset;
    margin-right: 5px;
}

:deep(.ant-tabs-card > .ant-tabs-nav .ant-tabs-tab-active > .ant-tabs-tab-btn){
    color: #1c64c0 !important;
}
</style>